package com.coderlin1.service.impl;

import cn.hutool.core.util.StrUtil;
import com.coderlin1.entities.Worker;
import com.coderlin1.mapper.WorkerMapper;
import com.coderlin1.service.WorkerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <Description> <br>
 *
 * @author Coder_Lin<br>
 * @version 1.0<br>
 * @taskId: <br>
 * @createDate 2021/08/03 14:28 <br>
 * @see com.coderlin1.service.impl <br>
 */
@Slf4j
@Service
public class WorkerServiceImpl implements WorkerService {

    @Autowired
    private WorkerMapper workerMapper;

    @Value("${location}")
    private String location;

    /**
     * 从数据库中查询出所有的worker信息
     *
     * @return
     */
    @Override
    public List<Worker> listWorker() {
        return workerMapper.listWorker();
    }

    /**
     * 将上传的文件传入服务器本地，并且对文件根据时间戳进行重命名
     *
     * @param worker
     * @param upLoadFile
     * @return
     */
    @Override
    public Integer addWorker(Worker worker, MultipartFile upLoadFile) throws IOException {

        if (log.isInfoEnabled()) {
            log.info(location);
        }
        String originalFileName = upLoadFile.getOriginalFilename();
        if(StrUtil.isNotEmpty(originalFileName)){
            int suffixIndex = originalFileName.lastIndexOf('.');
            long prefix = System.currentTimeMillis();
//            设置上传的文件在服务器端的路径
            String suffix = originalFileName.substring(suffixIndex);
            String fullFileName = prefix + suffix;
            File parentPath = new File(location);
            if(!parentPath.exists()){
                parentPath.mkdirs();
            }
            File resultPath = new File(parentPath, fullFileName);
            upLoadFile.transferTo(resultPath);
            worker.setWorkerImage(fullFileName);
        }

        return workerMapper.addWorker(worker);
    }
}
